/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.sharding.sample.masterslave.service;

import com.lvyh.lightframe.sharding.client.pagination.DefaultPageResult;
import com.lvyh.lightframe.sharding.client.pagination.PageParam;
import com.lvyh.lightframe.sharding.client.pagination.PageUtil;
import com.lvyh.lightframe.sharding.client.util.BeanUtil;
import com.lvyh.lightframe.sharding.client.util.Page;
import com.lvyh.lightframe.sharding.sample.masterslave.bean.UserBean;
import com.lvyh.lightframe.sharding.sample.masterslave.dao.entity.User;
import com.lvyh.lightframe.sharding.sample.masterslave.dao.entity.UserExample;
import com.lvyh.lightframe.sharding.sample.masterslave.dao.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lvyh 2021/08/01.
 */
@Service
public class ShardingMainDataService {

    private final static Logger logger = LoggerFactory.getLogger(ShardingMainDataService.class);

    @Autowired
    private UserMapper userMapper;

    public boolean deleteUser(Long id) throws Exception {
        if (id == null) {
            return false;
        }
        try {
            int updateNum = userMapper.deleteByPrimaryKey(id);
            return updateNum == 1;
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    public List<UserBean> selectUser(UserBean condition) throws Exception {
        List<UserBean> list = new ArrayList<UserBean>();
        try {
            UserExample example = new UserExample();
            UserExample.Criteria criteria = example.createCriteria();
            if (condition.getId() != null) {
                criteria.andIdEqualTo(condition.getId());
            }
            if (condition.getAge() != null) {
                criteria.andAgeEqualTo(condition.getAge());
            }

            List<User> queryDataItems = userMapper.selectByExample(example);
            if (CollectionUtils.isEmpty(queryDataItems)) {
                return list;
            }

            for (User user : queryDataItems) {
                list.add(BeanUtil.toBean(UserBean.class, BeanUtil.toMap(user)));
            }

        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
        return list;
    }

    public DefaultPageResult<UserBean> selectUserByCondition(UserBean condition, PageParam pageParam) throws Exception {
        if (pageParam == null) {
            throw new Exception("pageParam must need");
        }
        Page<User> page = PageUtil.startPage(pageParam);

        try {
            UserExample example = new UserExample();
            if (condition != null) {
                UserExample.Criteria criteria = example.createCriteria();
                if (condition.getId() != null) {
                    criteria.andIdEqualTo(condition.getId());
                }

            }

            List<User> queryDataItems = userMapper.selectByExample(example);
            DefaultPageResult<UserBean> result = new DefaultPageResult<>();
            if (queryDataItems == null || queryDataItems.size() == 0) {
                return result;
            }

            List<UserBean> list = new ArrayList<UserBean>();
            for (User user : queryDataItems) {
                list.add(BeanUtil.toBean(UserBean.class, BeanUtil.toMap(user)));
            }

            result.setResultList(list);
            result.setPageSize(page.getPageSize());
            result.setPageNo(page.getPageNum());
            result.setTotalCount((int) page.getTotal());
            result.setTotalPage(page.getPages());
            return result;
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    public int countUserByCondition(UserBean condition) throws Exception {
        try {
            UserExample example = new UserExample();
            if (condition != null) {
                UserExample.Criteria criteria = example.createCriteria();
                if (condition.getId() != null) {
                    criteria.andIdEqualTo(condition.getId());
                }


            }

            return userMapper.countByExample(example);
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    @Transactional(rollbackFor = {RuntimeException.class})
    public boolean updateUser(UserBean userBean) throws Exception {
        if (userBean == null || userBean.getId() <= 0) {
            return false;
        }
        try {
            User updateBean = BeanUtil.toBean(User.class, BeanUtil.toMap(userBean));
            int updateNum = userMapper.updateByPrimaryKeySelective(updateBean);
            return updateNum == 1;
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    public UserBean selectUserById(Long id) throws Exception {
        if (id <= 0) {
            return null;
        }
        try {
            User user = userMapper.selectByPrimaryKey(id);
            if (user == null) {
                logger.warn("not found data, tid:{}", id);
                return null;
            }
            return BeanUtil.toBean(UserBean.class, BeanUtil.toMap(user));
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    public Long saveUser(UserBean userBean) throws Exception {
        if (userBean == null) {
            return -1L;
        }
        try {
            User insertBean = BeanUtil.toBean(User.class, BeanUtil.toMap(userBean));
            userMapper.insertSelective(insertBean);
            return insertBean.getId();
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }
}
